package com.metersbonwe.basetest.core;

import java.lang.reflect.Method;

import com.metersbonwe.basetest.annotation.Destroy;
import com.metersbonwe.basetest.annotation.IndexField;
import com.metersbonwe.basetest.annotation.Init;
import com.metersbonwe.basetest.annotation.TestTask;
import com.metersbonwe.basetest.proxy.Proxys;

public class TaskProxy extends Task implements Runnable {


	private Object source;

	private Method taskMethod;
	private Method initMethod;
	private Method destroyMethod;

	public TaskProxy(Object source) {
		this.source = source;
		taskMethod = Proxys.getMethodByAnnotationClass(source, TestTask.class);
		initMethod = Proxys.getMethodByAnnotationClass(source, Init.class);
		destroyMethod = Proxys.getMethodByAnnotationClass(source, Destroy.class);
	}
 
	public Object getSource() {
		return source;
	}

	public void setSource(Object source) {
		this.source = source;
	}

	@Override
	public boolean task() {
		try {
			return (Boolean)taskMethod.invoke(source, new Object[] {});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void init() {
		try {
			Proxys.setFieldValueByAnnotation(source,super.index,IndexField.class);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
		if (initMethod == null)
			return;
		try {
			initMethod.invoke(source, new Object[] {});
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("init method invoke error");
		}
	}

	@Override
	public void destroy() {
		if (destroyMethod == null)
			return;
		try {
			destroyMethod.invoke(source, new Object[] {});
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("destroy method invoke error");
		}
	}

}
